﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace Pfz.RemoteGaming.Internal
{
	[Serializable]
	internal sealed class _InitializationData
	{
		internal Assembly[] _commonAssemblies;
		internal RemoteGameProperty[] _propertyInfos;

		internal void AddDefaultTypes(Serialization.BinarySerializer binarySerializer)
		{
			RemoteGameProperty._propertiesLock.EnterReadLock();
			try
			{
				foreach(var propertyInfo in RemoteGameProperty._properties)
					binarySerializer.AddDefaultTypeRecursive(propertyInfo._propertyType);
			}
			finally
			{
				RemoteGameProperty._propertiesLock.ExitReadLock();
			}

			List<Type> types = new List<Type>();
			foreach(var assembly in _commonAssemblies)
			{
				foreach(var type in assembly.GetTypes())
				{
					if (type.IsAbstract)
					{
						if (!type.IsSubclassOf(typeof(RemoteGameComponent)))
							continue;
					}
					else
					{
						if (!type.IsSubclassOf(typeof(RemoteGameRequest)))
							continue;

						if (!type.IsSerializable)
							continue;
					}

					types.Add(type);
				}
			}

			types.Sort((a, b) => a.FullName.CompareTo(b.FullName));
			foreach(var type in types)
				binarySerializer.AddDefaultType(type);
		}
	}
}
